﻿using System;
using System.Collections.Generic;
using System.Text;

namespace TCCHWLib.Commands
{
    public class TXCommitCommand : ICommand
    {
        bool shouldRollBack = false;

        public override object Execute(Processor processor)
        {
            processor.IsCommitReady = true;
            shouldRollBack = false;
            Chip.WriteToConsole("Request: " + processor.Name);
            Chip.Instance.Arbiter.RequestToken(processor);
            if (Chip.Instance.Arbiter.ProcessorWithToken == processor)
            {
                Chip.Instance.Arbiter.ReleaseToken(processor);
            }
            else
            {
                shouldRollBack = true;
            }

            return null;
        }
        public bool commit(Processor processor)
        {
            return true;
        }

        public override void UpdatePC(Processor processor)
        {
            processor.PC = -1;

            if (shouldRollBack && !processor.IsCommitReady)
            {
                processor.didRollback = true;
                processor.Rollback(true);

            }
        }
        public override string ToString()
        {
            return "TX-COMMIT";
        }
    }
}
